package pile.customer.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pile.customer.config.UserWebSocketServerUtil;
import pile.customer.entity.Information;
import pile.customer.entity.User;
import pile.customer.params.ReceivingInformation;
import pile.customer.service.ICustomerServiceInformationService;
import pile.customer.service.IInformationService;
import pile.customer.service.IUserService;
import pile.customer.service.IWeChatService;

import java.util.Date;

@Service
@Slf4j
public class CustomerServiceInformationServiceImpl implements ICustomerServiceInformationService {


    @Autowired
    private IInformationService informationService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IWeChatService wechatService;
    /**
     * 处理客服信息
     * @param receivingInformation
     */
    @Override
    public void processingMessages(ReceivingInformation receivingInformation) {
        try{
            //第一步先把数据存在数据库里面
            //插入数据库数据
            Information information = new Information();

            information.setMessage(receivingInformation.getMessage());
            information.setOpenId(receivingInformation.getOpenId());
            //类型
            information.setType(2);
            //图片类型
            information.setMessageType(receivingInformation.getMessageType());
            informationService.add(information);

            /*//判断客户是否存在链接
            boolean onLine = userWebSocketServerUtil.isOnLine(receivingInformation.getOpenId());
*/
          /*  if(!onLine){
                return;
           }*/
            //连接中 直接给他发送消息
            //userWebSocketServerUtil.sendInfo(JSONUtil.toJsonStr(receivingInformation), receivingInformation.getOpenId());
            //发送给微信服务器
            wechatService.sendMessage(receivingInformation);
            //修改用户表里面 未读消息数量
            User user = new User();
            //未读数量
            user.setUnreadQuantity(0);
            //是否已读
            user.setIsReply(3);
            //客服账号
            user.setCustomerServiceAccount(receivingInformation.getCustomerServiceAccount());
            //最后一次消息
            user.setLastMessage(receivingInformation.getMessage());
            //最后一次类型
            user.setLastMessageType(2);
            //最后一次消息时间
            user.setLastMessageTime(new Date());
            //信息类型
            user.setMessageType(receivingInformation.getMessageType());
            user.setOpenId(receivingInformation.getOpenId());

            UpdateWrapper queryWrapper = new UpdateWrapper();
            queryWrapper.eq("open_id",receivingInformation.getOpenId());
            userService.update(user,queryWrapper);

        }catch (Exception e){
            log.error("处理客服发送消息失败:",e);
        }

    }


}
